package com.chhuang.tutool.ui.activity

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.chhuang.tutool.R
import com.chhuang.tutool.adapter.SocketListAdapter
import com.chhuang.tutool.databinding.ActivityMainBinding
import com.chhuang.tutool.db.DatabaseHelper
import com.chhuang.tutool.modle.SocketBean
import com.gnetek.tool.base.BaseActivity
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.swallowsonny.convertextlibrary.ascii2ByteArray
import com.swallowsonny.convertextlibrary.toHexString
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.actionbar.TitleBar.ImageAction
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.error
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.uiThread

class MainActivity : BaseActivity() {
    companion object {
        private const val TAG = "MainActivity"
    }

    private val viewBinding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    //列表
    private var socketList = mutableListOf<SocketBean>()
    //列表适配器
    private val socketListAdapter = SocketListAdapter(mutableListOf(), ::onItemClick)

    private lateinit var socketTypeParams: Array<String>

    //数据库
    private val Context.database: DatabaseHelper get() = DatabaseHelper(this)

    override fun viewBinding(){
        setContentView(viewBinding.root)
    }

    override fun initView() {
        socketTypeParams = this.resources.getStringArray(R.array.socket_type)
        WidgetUtils.initRecyclerView(viewBinding.recyclerView)
        viewBinding.recyclerView.adapter = socketListAdapter
    }

    /**
     * 从跳转页面，返回结果，监听
     */
    private val requestDataLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            result.data?.let {
                if(it.getBooleanExtra("isChanged", false)){
                    initData()
                }
            }
        }
    }

    override fun initListener() {
        //titleBar禁用左侧的图标及文字， 右侧添加图标和监听
        viewBinding.titleBar.disableLeftView().addAction(object : ImageAction(R.drawable.ic_add_white){
            override fun performAction(view: View?) {//点击 加号 添加新的连接
//                startActivity<SocketEditActivity>()
                val intent = Intent(this@MainActivity, SocketEditActivity::class.java)
                requestDataLauncher.launch(intent)
            }
        })

        //下拉刷新，上拉加载更多
        viewBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                refreshLayout.layout.postDelayed({
//                    listAdapter.loadMore()
                    refreshLayout.finishLoadMore()
                }, 1000)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshLayout.layout.postDelayed({
                    //刷新 列表
                    socketListAdapter.refresh(socketList)
                    viewBinding.refreshLayout.finishRefresh()
                }, 1000)
            }
        })
        //设置刷新加载时禁止所有列表操作
        viewBinding.refreshLayout.setDisableContentWhenRefresh(true)
        viewBinding.refreshLayout.setDisableContentWhenLoading(true)

    }

    override fun initData() {
        doAsync {
            //运行耗时的后台任务
            val socketBeans = database.queryAll()
            uiThread{
                //需要在主线程执行的任务
                socketList = socketBeans.toMutableList()
            }
        }

        viewBinding.refreshLayout.autoRefresh()
    }

    /**
     * 列表item被点击，弹出菜单
     */
    private fun onItemClick(view: View, index: Int, o: Any){
        val bean = o as SocketBean
        BottomSheet.BottomListSheetBuilder(this)
            .setTitle("${socketTypeParams[bean.socketType]} ${bean.ip}:${bean.port} ${getString(R.string.menu_item)}")
            .addItem(R.drawable.ic_connect, getString(R.string.menu_connect_item) ,"connect")
            .addItem(R.drawable.ic_edit, getString(R.string.menu_edit_item) ,"edit")
            .addItem(R.drawable.ic_delete, getString(R.string.menu_delete_item) ,"delete")
            .setIsCenter(true)
            .setOnSheetItemClickListener { dialog: BottomSheet, itemView: View?, position: Int, tag: String? ->
                when(tag){
                    "connect"->{//打开连接
                        if(bean.socketType<3) {
                            dialog.dismiss()
                            startActivity<ConnectionActivity>("socketBean" to bean)
                        }else {
                            xToasts("Developing...")
                        }
                    }
                    "edit"->{
                        dialog.dismiss()
                        val intent = Intent(this, SocketEditActivity::class.java)
                        intent.putExtra("socketBean", bean)
                        requestDataLauncher.launch(intent)
//                        startActivity<SocketEditActivity>("socketBean" to bean)
                    }
                    "delete"->{//删除连接
                        MaterialDialog.Builder(this)
                            .iconRes(R.drawable.ic_delete)
                            .title(R.string.tip_delete_title)
                            .content(R.string.tip_delete_content)
                            .positiveText(R.string.dialog_lab_confirm)
                            .negativeText(R.string.dialog_lab_cancel)
                            .onPositive { _, _ ->
                                if(socketList.isNotEmpty()){
                                    if(database.deleteById(bean.id)) {
                                        socketList.removeAt(index)
                                        viewBinding.refreshLayout.autoRefresh()
                                    }else {
                                        xToasts(R.string.delete_failed, 0)
                                    }
                                }
                                dialog.dismiss()
                            }
                            .show()
                    }
                }

            }
            .build()
            .show()
    }

    /**
     * 按两下返回键的退出
     */
    private var exitTime:Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                toasts(R.string.press_back_again_finish)
                exitTime = System.currentTimeMillis()
            } else {
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}